package com.wimcorp.magic.client.input;

import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.fusesource.jansi.Ansi.Color;

import com.wimcorp.magic.client.CommandLineInterface;

public class MainSelector extends Selector implements Callable<Void> {
	
	public MainSelector(CommandLineInterface commandLineInterface) {
		super(commandLineInterface);
	}

	@Override
	public Void call() {
		return main();
	}

	private Void main() {
		String input = null;
		while (input == null) {
			try {
				getCommandLineInterface().printInstruction("Waiting... ");
				input =  getCommandLineInterface().getMainConsole().readLine();
				CommandLineParser parser = new DefaultParser();
				try {
					CommandLine line = parser.parse(getMainOptions(), input.split(" "));
					processCommands(getMainOptions(), line.getOptions());
				} catch (Exception e) {
					getCommandLineInterface().print(e.getMessage(), Color.RED);

				}
			} catch (CancellationException e) {
				try {
					synchronized (getCommandLineInterface().getMainConsole().getLock()) {
						getCommandLineInterface().getMainConsole().getLock().wait();
					}
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			} catch (InterruptedException e) {

			} finally {
				input = null;
			}
		}
		
		
		return null;

	}
	
	public Options getMainOptions() {
		Options options = new Options();
		options.addOption(getHelpOption());
		options.addOption(getPlayerListOption());
		options.addOption(getViewBattleFieldOption());
		options.addOption(getViewHandOption());
		options.addOption(getViewLifeOption());
		return options;
	}


	

}
